import React from 'react'
import Digit from "./Digit/Digit";
import './Countdown.css'
import {log} from "../../../utils/commonfunc";

const oneMinute = 60
const oneHour = 60 * oneMinute
const oneDay = oneHour * 24

class Countdown extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            remain: [],
            timer: null,
        }
    }

    componentDidMount() {
        this.initState()
    }
    componentWillUnmount() {
        this.state.timer && clearTimeout(this.state.timer)
    }

    initState = () => {
        const begin = this.props.begin
        const end = this.props.end
        let seconds = end - begin
        if (seconds > 0) {
            let h = Math.floor(seconds / oneHour)

            seconds = seconds - oneHour * h
            const m = Math.floor(seconds / oneMinute)
            seconds = seconds - oneMinute * m
            let oneday = this.props.oneday
            if (oneday) {
                if (h > 24) {
                    h = h % 24
                }
            }
            const remain = [
                {now: h,},
                {now: m, limit: 60,},
                {now: seconds, limit: 60},
            ]
            this.setState({
                remain,
            }, () => {
                this.tick()
            })
        } else {
            this.setState({
                remain: [{now:0},{now:0,},{now: 0,},]
            })
        }
    }

    minusOne = (remain, index) => {
        const data = remain[index]
        const now = data.now
        const limit = data.limit
        let next = now - 1
        if (next < 0) {
            if (limit) {
                next += limit
            } else {
                next = 0
            }
            if (index > 0) {
                this.minusOne(remain, index - 1)
            }
        }
        remain[index] = {
            ...data,
            now: next,
        }
    }

    tick = () => {
        let id = setTimeout(() => {
            const remain = this.state.remain
            this.minusOne(remain, remain.length - 1)
            this.setState({
                remain,
                timer: id,
            }, () => {
                if (remain.every(d => d.now === 0)) {
                    clearTimeout(this.state.timer)
                } else {
                    id = this.tick()
                    this.setState({
                        timer: id,
                    })
                }
            })
        }, 1000)
        return id
    }

    render() {

        const remain = this.state.remain

        return <div className="countdown-container flex-center-align-center">
            {remain.map((d, i) => <Digit now={d.now} key={i} isLast={i === remain.length - 1} textStyle={{...this.props.textStyle}} textContainerStyle={{...this.props.textContainerStyle,}}/>)}
        </div>
    }
}

export default Countdown